package com.capsulode.excel.conversion.impl;

import com.capsulode.excel.conversion.Converter;
import com.capsulode.excel.exception.CellTypeNotExpectException;
import com.capsulode.excel.exception.ConversionFailException;
import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DictionaryConverter implements Converter {
    private final Class type;
    private final String[] raw;
    private final Map<String, Integer> dictionary;

    public DictionaryConverter(String[] dict, Class type) {
        raw=dict;
        dictionary = IntStream.range(0, dict.length)
                .boxed()
                .filter(i -> dict[i] != null && dict[i].length() > 0)
                .collect(Collectors.toMap(i -> dict[i], Function.identity(), (o, o2) -> o));
        this.type = type;
    }

    @Override
    public Object convert(Cell cell) throws ConversionFailException, CellTypeNotExpectException {
        if (CellType.STRING.equals(cell.getCellTypeEnum())) {
            String stringCellValue = cell.getStringCellValue();
            if (stringCellValue.isEmpty()) {
                return null;
            }
            Integer value = dictionary.get(stringCellValue);
            if (value == null) {
                throw new ConversionFailException(cell.getRowIndex(), cell.getColumnIndex(), "不支持的字典值：" + cell);
            }
            try {
                return ConvertUtils.convert(value, type);
            } catch (ConversionException ex) {
                throw new ConversionFailException(cell.getRowIndex(), cell.getColumnIndex(), "字典值字段类型无效", ex);
            }
        }

        if (CellType.BLANK.equals(cell.getCellTypeEnum())) {
            return null;
        }


        throw new CellTypeNotExpectException(cell.getRowIndex(), cell.getColumnIndex());
    }

    @Override
    public void serialize(Object value, Cell cell) throws ConversionFailException, CellTypeNotExpectException {
        Integer dictIndex=null;
        if(value instanceof Number){
            dictIndex=((Number)value).intValue();
        }else if(value instanceof CharSequence){
            dictIndex=Integer.parseInt(value.toString());
        }

        if(dictIndex==null){
            throw new CellTypeNotExpectException(cell.getRowIndex(), cell.getColumnIndex());
        }
        String val=raw[dictIndex];
        cell.setCellValue(val);
    }
}
